﻿create PROCEDURE Sync.SP_IssuePlace_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @IssuePlace_Temp TABLE 
		(
			IssuePlaceID UniqueIdentifier,
			[IssuePlaceName] nvarchar(50),
				[CenterID] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @IssuePlace_Temp 
	   SELECT	Tbl.Col.value('IssuePlaceID[1]','uniqueidentifier') IssuePlaceID,
                Tbl.Col.value('IssuePlaceName[1]', 'nvarchar(50)') [IssuePlaceName],
Tbl.Col.value('CenterID[1]', 'uniqueidentifier') [CenterID],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/IssuePlace') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[IssuePlace] ([IssuePlaceID],[IssuePlaceName],[CenterID])
	SELECT t.[IssuePlaceID],t.[IssuePlaceName],t.[CenterID]
	FROM  @IssuePlace_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.IssuePlace_Tracking s
        WHERE t.IssuePlaceID = s.IssuePlaceID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[IssuePlace]
	SET [IssuePlace].[IssuePlaceName] = t.[IssuePlaceName],[IssuePlace].[CenterID] = t.[CenterID] 
	FROM [dbo].[IssuePlace] s JOIN @IssuePlace_Temp t 
    ON t.IssuePlaceID = s.IssuePlaceID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.IssuePlace_Tracking r
				  WHERE t.IssuePlaceID = r.IssuePlaceID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[IssuePlace]
    FROM @IssuePlace_Temp t JOIN [dbo].[IssuePlace] s
    ON t.IssuePlaceID = s.IssuePlaceID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END





